const util = require('../../utils/util.js');
const wxHttpHandler = require('../../utils/wxHttpHandler.js');
const api = require('../../APIConfig/apiConfig.js');

var app = getApp();

Page({
  data: {
    vehicleId: -1,
    registerNo: '',
    devices: [],
    isShowList: false,
    selelctDevice: null
  },

  onLoad: function (options) {
    this.setData({
      vehicleId: options.vehicleId,
      registerNo: options.registrationNO
    })
    this.unbindTerminalList()
  },

  onShow: function () {

  },

  selectDeviceTap: function (e) {
    if (!this.data.isShowList) {
      this.setData({
        isShowList: true
      })
    } else {
      this.setData({
        isShowList: false
      })
    }
  },

  listViewTap: function (e) {
    this.setData({
      selelctDevice: e.currentTarget.dataset.a,
      isShowList: false
    })
  },

  submit: function (e) {
    let that = this
    if(this.data.selelctDevice ==null){
      wx.showToast({
        title: '请选择设备通讯号',
      })
      return
    }
    wx.showModal({
      title: '解绑',
      content: '确定解绑该设备？',
      success: (res) => {
        if (res.confirm) {
          that.unbindTerminalVehicle()
        }
      }
    })
  },


  //设备通讯号列表
  unbindTerminalList: function () {
    let data = {
      vehicleId: this.data.vehicleId,
    }
    const that = this
    wx.showLoading()
    wxHttpHandler({
      type: 'get',
      path: api.unbindTerminalList,
      data: data,
      fn: function (res) {
        if (res.code == 0) {
          if (res.data != null && res.data.length > 0) {
            that.setData({
              devices: res.data,
              selelctDevice: res.data[0]
            })
          }
          wx.hideLoading()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.desc,
            icon: 'none',
            duration: 1500,
            mask: true
          });
        }
      }

    })
  },


  //解绑设备
  unbindTerminalVehicle: function () {
    let data = {
      uid: wx.getStorageSync('id'),
      id: this.data.vehicleId,
      vehicleId: this.data.vehicleId,
    }
    const that = this
    wx.showLoading()
    wxHttpHandler({
      type: 'get',
      path: api.unbindTerminalVehicle,
      data: data,
      fn: function (res) {
        if (res.code == 0) {
          wx.showToast({
            title: res.data,
          })
          wx.navigateBack({
            complete: (res) => {},
          })
          wx.hideLoading()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.desc,
            icon: 'none',
            duration: 1500,
            mask: true
          });
        }
      }

    })
  },
})